import { login, getInfo, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken, setTimeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
    setTimeToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  logout(state) {
    state.userInfo = {}
    state.token = null
    removeToken()
  }
}

const actions = {
  // 登录
  async login(context, payload) {
    const res = await login(payload)
    context.commit('setToken', res)
  },
  // 获取用户资料
  async getUserInfo(context) {
    const res = await getInfo()
    const data = await getUserInfo(res.userId)
    context.commit('setUserInfo', { ...res, ...data })
    return res
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
